﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    tcpServer = new QTcpServer(this);
    connect(tcpServer,&QTcpServer::newConnection,this,&MainWindow::TcpServerConnected);

    QList<QHostAddress> addrList = QNetworkInterface::allAddresses();
    foreach(const QHostAddress &address,addrList)
    {
        if(address.protocol() == QAbstractSocket::IPv4Protocol)
        {
            ui->combAddress->addItem(address.toString());
        }
    }
}

MainWindow::~MainWindow()
{
    delete ui;
    for(auto client : tcpSocketList)
        client->close();
}


void MainWindow::on_btnRun_clicked()
{
    QHostAddress address = QHostAddress(ui->combAddress->currentText());
    int port = ui->txtPort->text().toInt();
    if(tcpServer->isListening())
    {
        for(auto client : tcpSocketList)
            client->disconnectFromHost();
        tcpSocketList.clear();
        tcpServer->close();
        ui->label->setText(QString("关闭监听成功，%1:%2").arg(address.toString()).arg(port));
        ui->btnRun->setText("开启");
        ui->txtPort->setEnabled(true);
        ui->combAddress->setEnabled(true);
    }
    else
    {
        if(!tcpServer->listen(address,port))
            ui->label->setText(QString("开启监听失败，%1:%2").arg(address.toString()).arg(port));
        else
        {
            ui->label->setText(QString("开启监听成功，%1:%2").arg(address.toString()).arg(port));
            ui->btnRun->setText("关闭");
            ui->txtPort->setEnabled(false);
            ui->combAddress->setEnabled(false);
        }
    }

}

void MainWindow::TcpServerConnected()
{
    tcpSocket = tcpServer->nextPendingConnection();
    if(!tcpSocketList.contains(tcpSocket))
        tcpSocketList.append(tcpSocket);
    connect(tcpSocket,&QTcpSocket::readyRead,this,&MainWindow::ReadAllData);
    connect(tcpSocket,&QTcpSocket::disconnected,this,&MainWindow::ClientDisconnected);
    ui->txtLog->append(tcpSocket->peerAddress().toString() + ":" + tcpSocket->peerPort() + " 已连接");
}

void MainWindow::ReadAllData()
{
    QTcpSocket *client = dynamic_cast<QTcpSocket*>(sender());
    QByteArray buff = client->readAll();
    qDebug() << buff;
    ui->txtLog->append(buff);
    client->write(buff);
}

void MainWindow::ClientDisconnected()
{
    QTcpSocket *client = dynamic_cast<QTcpSocket*>(sender());
    QString msg = QString("触发断开连接,%1:%2").arg(client->peerAddress().toString()).arg(client->peerPort());
    qDebug() << msg;
    ui->txtLog->append(msg);
}
